package com.tjetc.utils;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @Author: itda
 * @Date: 2024/5/11 21:40
 * @Description: POI数据导出
 */
public class ExcelUtil {

    /**
     * 导出数据到Excel文件
     * @param fileName 文件名
     * @param headers 表头
     * @param data 数据
     * @throws IOException
     */
    public static void exportToExcel(String fileName, List<String> headers, List<List<Object>> data,String sheetName) throws IOException {
        // 创建一个新的Excel工作簿
        Workbook workbook = new XSSFWorkbook();

        // 在工作簿中创建一个新的工作表
        Sheet sheet = workbook.createSheet(sheetName);

        // 添加表头行
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            headerRow.createCell(i).setCellValue(headers.get(i));
        }

        // 添加数据行
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < data.get(i).size(); j++) {
                row.createCell(j).setCellValue(data.get(i).get(j).toString());
            }
        }

        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭工作簿
        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}